<template>
  <!-- 批量变更报价 -->
  <a-modal :width="1000" v-model:visible="showEditDialog" title="批量变更" top="8vh" title-align="start" :on-before-ok="submitData" :ok-loading="submitLoading" :mask-closable="false" @cancel="closedDialog">
    <p style="margin-bottom: 5px">对已选中报价单，做出以下变更，变更单需经过供应商和经销商双方同意之后方可生效；</p>
    <a-textarea style="margin-bottom: 10px" v-model="formInfo.remark" placeholder="变更原因" allow-clear />
    <div class="change-header flex-c">
      <p style="width: 120px">可变更项目</p>
      <p style="width: 300px">变更内容</p>
    </div>
    <a-checkbox-group direction="vertical" v-model="checkedType">
      <ul class="change-list">
        <li class="flex-c">
          <p style="width: 120px"><a-checkbox value="invoiceType">发票类型</a-checkbox></p>
          <a-select v-model="formInfo.invoiceType" placeholder="发票类型" style="width: 200px">
            <a-option :value="1" label="普票" />
            <a-option :value="2" label="专票" />
            <a-option :value="0" label="不开票" />
          </a-select>
        </li>
        <li class="flex-c">
          <p style="width: 120px"><a-checkbox value="parTaxRate">税率</a-checkbox></p>
          <div class="flex-c">
            <a-input-number style="width: 200px" v-model="formInfo.parTaxRate" :precision="0" placeholder="" :min="0" />
            <span style="margin-left: 5px">%</span>
          </div>
        </li>
        <li class="flex-c">
          <p style="width: 120px"><a-checkbox value="currency">币种</a-checkbox></p>
          <a-select style="width: 200px" v-model="formInfo.currency" placeholder="币种" allow-search>
            <a-option :value="item" :label="item" v-for="(item, i) in Object.keys(currencySymbol)" :key="i" />
          </a-select>
        </li>
        <li class="flex-c">
          <p style="width: 120px"><a-checkbox value="deliveryDays">交期</a-checkbox></p>
          <div class="flex-c">
            <a-input-number style="width: 200px" v-model="formInfo.deliveryDays" :precision="0" placeholder="" :min="0" />
            <span style="margin-left: 5px">天</span>
          </div>
        </li>
        <li class="flex-c">
          <p style="width: 120px"><a-checkbox value="moq">起订量</a-checkbox></p>
          <a-input-number style="width: 200px" v-model="formInfo.moq" :precision="0" placeholder="" :min="0" />
        </li>
        <li class="flex">
          <p style="width: 120px"><a-checkbox value="quoteType">报价类型</a-checkbox></p>
          <div style="width: 750px">
            <a-select style="width: 200px" v-model="formInfo.quoteType" placeholder="">
              <a-option :value="1" label="非梯度报价" />
              <a-option :value="2" label="梯度报价" />
            </a-select>
            <div class="price-wrap" style="height: calc(84vh - 540px)">
              <div class="flex-c" style="flex: 1; margin-top: 10px" v-if="formInfo.quoteType === 1">
                <p>
                  <span class="warningColor">*</span>
                  <span>含税单价：</span>
                </p>
                <a-radio-group style="flex: 1" class="flex-c" v-model="changePriceType">
                  <div class="flex-c">
                    <a-radio :value="1">直接修改为</a-radio>
                    <span style="margin-right: 5px">{{ currencySymbol[formInfo.currency] || '￥' }}</span>
                    <a-input-number style="width: 100px" v-model="priceVal" :precision="2" placeholder="" :min="0" />
                  </div>
                  <div class="flex-c" style="margin-left: 20px">
                    <a-radio :value="2">在原基础上</a-radio>
                    <a-select style="width: 100px" v-model="adjustType" placeholder="">
                      <a-option :value="1" label="提高" />
                      <a-option :value="-1" label="降低" />
                    </a-select>
                    <a-input-number style="width: 100px" v-model="adjustPrice" :precision="2" placeholder="" :min="0" />
                    <span>%</span>
                  </div>
                </a-radio-group>
              </div>
              <a-table v-else style="margin-top: 10px" class="table-singe-line" ref="tableRef" row-key="id" :data="formInfo.quoteItems" size="mini" :bordered="false" :pagination="false">
                <template #columns>
                  <a-table-column :width="120">
                    <template #title>
                      <p>
                        <span class="warningColor">*</span>
                        <span>数量</span>
                      </p>
                    </template>
                    <template #cell="{ record }">
                      <span style="margin-right: 5px">>=</span>
                      <a-input-number v-model="record.quantity" style="width: 100px" :precision="0" placeholder="请输入" :min="0" />
                    </template>
                  </a-table-column>
                  <a-table-column :width="120">
                    <template #title>
                      <p>
                        <span class="warningColor">*</span>
                        <span>含税单价</span>
                      </p>
                    </template>
                    <template #cell="{ record }">
                      <span style="margin-right: 5px">{{ currencySymbol[formInfo.currency] || '￥' }}</span>
                      <a-input-number v-model="record.taxPrice" style="width: 100px" :precision="2" placeholder="请输入" :min="0" />
                    </template>
                  </a-table-column>
                  <a-table-column title="操作" :width="100">
                    <template #cell="{ rowIndex }">
                      <a-space>
                        <a-button type="text" @click="formInfo.quoteItems.splice(rowIndex + 1, 0, {})">添加</a-button>
                        <a-button type="text" v-if="formInfo.quoteItems.length > 1" @click="formInfo.quoteItems.splice(rowIndex, 1)">移除</a-button>
                      </a-space>
                    </template>
                  </a-table-column>
                </template>
              </a-table>
            </div>
          </div>
        </li>
      </ul>
    </a-checkbox-group>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref } from 'vue'
  import { changeSupplierPurchaseQuote } from '@/api/supplier'
  import { currencySymbol } from '@/utils/globalData'
  import { Message } from '@arco-design/web-vue'
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    currentList: {
      type: Array,
      default: () => [],
    },
  })

  const showEditDialog = ref(props.isShow)
  const changePriceType = ref(1)
  const adjustType = ref(1)
  const adjustPrice = ref()
  const priceVal = ref()
  const checkedType = ref<Array<string>>([])
  const formInfo = ref<any>({
    quoteItems: [{}],
    quoteType: 1,
  })
  const submitLoading = ref(false)

  // 修改单价关联
  function changePrice(item: any, row: any) {
    // 如果变更里有税率，则取最新税率，如果没有则取原税率
    let parTaxRate = checkedType.value.includes('parTaxRate') ? formInfo.value.parTaxRate || 0 : row.parTaxRate || 0
    // 修改含税单价
    let val = Number(((item.taxPrice || 0) / (1 + parTaxRate / 100)).toFixed(2))
    item.price = val
  }

  // 关闭
  function closedDialog() {
    emit('closed')
  }

  function isNull(val: any) {
    return val === undefined || val === null || val === ''
  }

  // 校验必填信息
  function validation() {
    if (!checkedType.value.length) {
      Message.error('请最少选择一个变更项')
      return false
    }
    for (let key of checkedType.value) {
      if (isNull(formInfo.value[key])) {
        Message.error('变更项内容必填')
        return false
      }

      if (key == 'quoteType') {
        // 非梯度报价校验
        if (formInfo.value.quoteType === 1) {
          if (changePriceType.value === 1 && isNull(priceVal.value)) {
            Message.error('直接修改含税单价金额必填')
            return false
          }
          if (changePriceType.value === 2 && isNull(adjustPrice.value)) {
            Message.error('原基础上提高百分比必填')
            return false
          }
        } else {
          // 梯度报价校验
          for (let item of formInfo.value.quoteItems) {
            if (isNull(item.taxPrice) || isNull(item.quantity)) {
              Message.error('梯度报价数量，含税单价必填')
              return false
            }
          }
        }
      }
    }
    return true
  }
  function setSavePriceData(row: any) {
    let priceItems = []
    if (formInfo.value.quoteType === 1) {
      let priceInfo: any = {}
      if (changePriceType.value == 1) {
        // 直接调整含税单价
        priceInfo.taxPrice = priceVal.value
      } else {
        // 在原有基础提高或降低
        let taxPrice = row.quoteItems?.[0]?.taxPrice || 0
        priceInfo.taxPrice = (((100 + adjustPrice.value * adjustType.value) / 100) * taxPrice).toFixed(2)
      }
      changePrice(priceInfo, row)
      priceItems.push(priceInfo)
    } else {
      priceItems = formInfo.value.quoteItems.map((el: any) => {
        changePrice(el, row)
        return el
      })
    }
    return priceItems
  }
  // 保存信息
  async function submitData() {
    let flag = validation()
    if (!flag) return false
    let changeItems: Array<any> = []
    props.currentList.forEach((el: any) => {
      let item = JSON.parse(JSON.stringify(el))
      item.changeType = 'quote'
      item.remark = formInfo.value.remark
      checkedType.value.forEach((key: string) => {
        item[key] = formInfo.value[key]
        if (key == 'quoteType') {
          item.quoteItems = setSavePriceData(item)
        }
      })
      changeItems.push(item)
    })
    const res = await changeSupplierPurchaseQuote({ changeItems })
    if (!res) return false
    Message.success('保存成功')
    emit('success')
    closedDialog()
  }
</script>
<style lang="less" scoped>
  .change-header {
    background: #f5f5f5;
    padding: 5px 5px;
  }
  .change-list {
    width: 900px;
    li {
      margin-top: 5px;
    }
  }
  :deep(.arco-form-item-label-col) {
    padding-right: 0;
  }
</style>
